#!/usr/bin/env python 
# -*- coding: utf-8 -*-
# @Time    : 2023/4/7 16:54
# @Author  : WJQ
# @Site    : 
# @File    : instrument.py
# @Software: PyCharm
import os
import time
from datetime import datetime
import conf
from browser.driver_wx import DriverHandlerWx
from utils.common import CrawlerLogger


def back_previous_page(driver):
    driver.press_keycode(4)
    CrawlerLogger.info("[*] Back to previous page")
    time.sleep(2)

def back_init_page(driver_handler: DriverHandlerWx, init_title, applets_name):
    """
    Back to init page
    :param driver_handler:
    :param init_title:
    :return:
    """
    CrawlerLogger.info("[*] Back to init page")
    flag = 0
    # driver_handler.switch_to_webview_context()
    while driver_handler.driver.path != init_title and flag < 10:
        back_previous_page(driver_handler.driver)
        driver_handler.find_top_window()
        flag += 1
    if flag < 10:
        # driver_handler.switch_to_native_app_context()
        driver_handler.switch_to_webview_context()
        return
    else:
        driver_handler.enter_mini_program(applets_name)
        return

def capture_screenshot(driver, filename, applets_name=None,timestamp=None):
    # 获取当前时间并格式化为字符串（例如：2024-01-02_15-30-00）
    current_time = timestamp or datetime.now().strftime("%Y-%m-%d_%H-%M-%S")

    # 处理文件名中的非法字符，将斜杠替换为下划线
    safe_filename = filename.replace('/', '_').replace('\\', '_')

    # 构建目标文件夹路径
    platform_folder = conf.CLIENT_SIDE_CONF.PLATFORM
    
    if applets_name:
        target_folder = os.path.join("logs", platform_folder, "res", applets_name)
    else:
        target_folder = os.path.join("logs", platform_folder, "res")
        
    os.makedirs(target_folder, exist_ok=True)  # 确保目标文件夹存在

    # 将当前时间添加到文件名中
    new_filename = f"{safe_filename}_{current_time}.png"  # 假设截图总是以.png格式保存

    # 构建目标文件路径
    target_path = os.path.join(target_folder, new_filename)
    
    try:
        result = driver.save_screenshot(target_path)
        if result:
            CrawlerLogger.info(f"[*] Screenshot saved in {target_path}")
        else:
            CrawlerLogger.error(f"[*] Failed to save screenshot to {target_path}")
    except Exception as e:
        CrawlerLogger.error(f"[*] Screenshot error: {e}")
    
    return target_path